import os
# import HTMLTestRunner  #  未改编
import sys
import unittest

path = os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0]
sys.path.append(path)

from commond import HTMLTestRunner as HTMLTestRunner, get_path_info
from commond import log_config
from commond import read_config
from commond.config_email import Sendmail

project_name = "WP"
readconfig = read_config.ReadConfig("config.ini", project_name)
project_case_path = get_path_info.get_test_project(project_name)
result_path = os.path.join(project_case_path, "result")
report_name = readconfig.get_project_info('PROJECT', 'report_name')
report_path = os.path.join(result_path, report_name)
on_off = readconfig.get_email("EMAIL", 'on_off')
log = log_config.Logger().get_logger(result_path)
send_email = Sendmail("config.ini", project_name)


class AllTest(object):
    def __init__(self):
        global resultPath
        resultPath = result_path
        self.caseListFile = os.path.join(project_case_path, "testfile", "caselist.txt")  # 配置执行哪些测试文件的配置文件路径
        self.caseFile = project_case_path  # 测试用例脚本路径
        self.caseList = []

    def set_case_list(self):
        """
        读取caselist.txt文件中的用例名称，并添加到caselist元素组
        :return:
        """
        fb = open(self.caseListFile)
        for value in fb.readlines():
            data = str(value)
            if data != '' and not data.startswith("#"):
                self.caseList.append(data.replace("\n", ""))  # 读取每行数据会将换行转换为\n，去掉每行数据中的\n\
                # print(self.caseList)
        fb.close()

    def set_case_suite(self):
        """

        :return:
        """
        self.set_case_list()
        test_suite = unittest.TestSuite()
        suite_module = []
        for case in self.caseList:  # 从caselist元素组中循环取出case
            case_name = case.split("/")[-1]  # 通过split函数来将aaa/bbb分割字符串，-1取后面，0取前面
            # 批量加载用例，第一个参数为用例存放路径，第一个参数为 路径文件名
            discover = unittest.defaultTestLoader.discover(self.caseFile, pattern=case_name + '.py', top_level_dir=None)
            suite_module.append(discover)  # 将discover存入suite_module元素组
        if len(suite_module) > 0:
            for suite in suite_module:
                for test_name in suite:  # 从discover中取出test_name，使用addTest添加到测试集
                    test_suite.addTest(test_name)
        else:
            print('else:')
            return None
        return test_suite  # 返回测试集

    def run(self):
        """
        run test
        :return
        """

        try:
            suit = self.set_case_suite()
            if suit is not None:
                print(report_path)
                with open(report_path, 'wb') as fp:
                    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, verbosity=2, title='Test Report',
                                                           description='Test Description')
                    # runner = unittest.TextTestRunner(stream=None, descriptions=None, verbosity=2)
                    runner.run(suit)

            else:
                print("Have no case to test.")
        except Exception as ex:
            print(str(ex))
            log.info(str(ex))

        finally:
            print("*********TEST END*********")

            # log.info("*********TEST END*********")
            fp.close()
            # print(on_off)
            # 判断邮件发送的开关
            if on_off == "on":
                send_email.send_email(report_path)
            else:
                print("邮件发送开关配置关闭，请打开开关后可正常自动发送测试报告")


if __name__ == '__main__':
    AllTest().run()
